#include "Precomp.h"
#include "SquirrelHelper.h"
#include <sstream>

void tableToString(SquirrelObject& table,wstring& answer)
{
	answer+=L"{\n";//start of a table
	SquirrelObject key,val;
	table.BeginIteration();
	wstring subtable;
	while(table.Next(key,val))
	{
		//SquirrelVM::PrintFunc(SquirrelVM::GetVMPtr(),L"%s=%s",key.ToString(),val.ToString());
		SQObjectType valtype=val.GetType();
		if((key.GetType()==OT_STRING)//only support string key
			&&((valtype==OT_STRING)||(valtype==OT_TABLE)||(valtype==OT_INTEGER)||(valtype==OT_FLOAT)||(valtype==OT_BOOL)
			))
		{
			answer+=key.ToString();
			answer+=L"=";
			switch(val.GetType())
			{
			case OT_STRING:
				answer+=L'\"';
				answer+=val.ToString();
				answer+=L'\"';
			break;
			case OT_TABLE:

				tableToString(val,subtable);
				answer+=subtable;
			break;
			case OT_INTEGER:
			case OT_FLOAT:
			case OT_BOOL:
				HSQUIRRELVM vm=SquirrelVM::GetVMPtr();
				int top=sq_gettop(vm);
				sq_pushroottable(vm);
				sq_pushobject(vm,val.GetObjectHandle());
				sq_tostring(vm,-1);
				const SQChar* str;
				sq_getstring(vm,-1,&str);
				answer+=str;
				sq_settop(vm,top);
			break;
			}
			answer+=L"\n";
		}
	}
	table.EndIteration();
	answer+=L'}';//end of the table
}